package com.myself.service;

import com.myself.entity.User;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Component;

/**
 * Description:
 *
 * @Author: Liuzemin
 * @Date: 2020/7/15 9:48
 */
@Component
public class PasswordHelper {
  private SecureRandomNumberGenerator rng = new SecureRandomNumberGenerator();

  private String algorithmName = "md5";

  private Integer hashInterations = 2;

    public SecureRandomNumberGenerator getRng() {
        return rng;
    }

    public void setRng(SecureRandomNumberGenerator rng) {
        this.rng = rng;
    }

    public String getAlgorithmName() {
        return algorithmName;
    }

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public Integer getHashInterations() {
        return hashInterations;
    }

    public void setHashInterations(Integer hashInterations) {
        this.hashInterations = hashInterations;
    }

    public void encryptPassword(User user){
        if (user.getPassword() != null){
            user.setSalt(rng.nextBytes().toHex());

            String newPassword = new SimpleHash(algorithmName,
                    user.getPassword(),
                    user.getCredentialsSalt(),
                    hashInterations).toHex();

            user.setPassword(newPassword);
        }
    }
}
